import JSEncrypt from "jsencrypt";

import CryptoJS from "crypto-js";
const pk =
  "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAAfFtmTRX6EXbI5NXWxkXy37FXJt3ivy85eMd6zO2LtAMCgfgY5BB8xXex3CF0SJP42QKGmTx+1VYBOLTqxE/e/d5cjtAXPqIrvJAWHvadQHjAjlUdlRcku5ZxWtHyFN/8bFKqsnxDPO9Qub7eShVhY77mIssY7bo3/DLkfU8vwIDAQAB";
const encrypt = (string) => {
  const encryptor = new JSEncrypt();
  encryptor.setPublicKey(pk);
  const encryptResult = encryptor.encrypt(string);
  return encryptResult;
};

const timer16 = () => {
  let timestamp = new Date().getTime();
  // 例如：1640843589105，单位是毫秒
  // 转换成16进制字符串
  let timestamp_hex = timestamp.toString(16);
  return timestamp_hex;
};

// 随机生成 32 位
const getUuid = () => {
  return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

// 转16 进制
const stringToHex = (data) => {
  let str16 = parseInt(data, 16);
  return str16;
};

const encryptByDES = (message) => {
  let key = getUuid();
  let iv = key.substring(key.length - 7, key.length);
  let ivHex = CryptoJS.enc.Utf8.parse(iv);
  let keyHex = CryptoJS.enc.Utf8.parse(key);
  let encrypted = CryptoJS.DES.encrypt(message, keyHex, {
    iv: ivHex,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return {
    key: key + timer16() + stringToHex(iv) + getUuid(),
    value: encrypted.ciphertext.toString(),
  };
};

const decryptByDES = (ciphertext) => {
  let iv = ciphertext.substring(ciphertext.length - 52, ciphertext.length - 41);
  let key = ciphertext.substring(ciphertext.length - 32, ciphertext.length);
  let value = ciphertext.substring(0, ciphertext.length - 52);
  let keyHex = CryptoJS.enc.Utf8.parse(key);
  let ivHex = CryptoJS.enc.Utf8.parse(iv);
  let decrypted = CryptoJS.DES.decrypt(
    {
      value: CryptoJS.enc.Hex.parse(value),
    },
    keyHex,
    {
      iv: ivHex,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    }
  );
  let result_value = decrypted.toString(CryptoJS.enc.Utf8);
  console.log(result_value, "2");
  return result_value;
};

export { encrypt, encryptByDES, decryptByDES };
